<template>
  <div class="container">
    <div class='stockProperty'>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card>
            <div slot="header" class="clearfix">
              <el-input v-model="filterText" placeholder="输入关键字进行过滤"></el-input>
            </div>
            <div class="card-body">
              <el-tree ref="tree" :props="defaultProps" :data="treedata" :highlight-current="true" node-key="id" :default-expand-all="true" :filter-node-method="filterNode2" @node-click="getNodeData">
              </el-tree>
            </div>
          </el-card>
        </el-col>
        <el-col :span="20">
          <el-row :gutter="6" style="margin-bottom: 10px">
            <el-col :span="24">
              <el-card>
                <div style="margin-top: 20px">
                  <el-form class="filter-container" label-position="left" label-width="68px">
                    <el-row :gutter="24">
                      <el-col :span="12">
                        <el-form-item label="股票代码" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.code" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodcode" class="filter-item"
                            placeholder="输入关键词">
                            <el-option v-for="item in stockcodeOptions" :key="item.tag_code" :label="item.name+(item.code)" :value="item.code">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="股票名称" style="margin-bottom: 0 !important">
                          <el-select v-model="listQuery.name" value-key="tag_code" clearable filterable remote reserve-keyword :loading="loading" :remote-method="remoteMethodname" class="filter-item"
                            placeholder="输入关键词">
                            <el-option v-for="item in stocknameOptions" :key="item.tag_code" :label="item.name" :value="item.name">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12">
                        <el-form-item label="近似词" style="margin-bottom: 0 !important">
                          <el-input @keyup.enter.native="getList" class="filter-item" placeholder="输入关键词" v-model.trim="listQuery.similarWord"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="状态" style="margin-bottom: 0 !important">
                          <el-select clearable v-model="listQuery.state" placeholder="请选择">
                            <el-option value label="全部"></el-option>
                            <el-option :value="1" label="启用"></el-option>
                            <el-option :value="0" label="停用"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row style="float: right">
                      <el-col :span="8"></el-col>
                      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
                      <el-button class="filter-item el-icon-refresh" style="margin-left: 10px" @click="resetSearch" type="primary">重置</el-button>
                    </el-row>
                  </el-form>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="24">
              <el-card>
                <div slot="header"></div>
                <div>
                  <div style="margin-bottom: 12px">
                    <el-button style="margin-right: 10px" @click="handleAdd" type="primary" disabled>新增</el-button>
                    <el-button style="margin-right: 10px" @click="handleStart" type="primary">启用</el-button>
                    <el-button style="margin-right: 10px" @click="handleStop" type="primary">停用</el-button>
                    <el-button style="margin-right: 10px" @click="alldelete" type="primary">批量删除</el-button>
                    <a :href="downloadInfo.url" :download="downloadInfo.name">
                      <el-button type="warning" icon="el-icon-download">下载Excel模板</el-button>
                    </a>
                    <el-button :loading="true" v-if="!!uploadFileInfo.loading" type="warning">上传中</el-button>
                    <el-upload ref="uploadButton" :action="uploadAction" accept=".xlsx, .xls" :headers="{
                        Authorization: 'Bearer ' + $store.getters.token,
                      }" style="display: inline" :on-success="startParse" :before-upload="beforeUpload">
                      <el-button v-if="!uploadFileInfo.loading" type="success" icon="el-icon-upload">上传Excel</el-button>
                    </el-upload>
                  </div>
                  <el-table stripe :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit highlight-current-row @selection-change="handleSelectionChange"
                    style="width: 100%">
                    <el-table-column align="center" type="selection" width="55"></el-table-column>
                    <el-table-column align="center" label="标签代码">
                      <template slot-scope="scope">
                        <span>{{ scope.row.tagCode }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="股票代码">
                      <template slot-scope="scope">
                        <span>{{ scope.row.code }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="股票名称">
                      <template slot-scope="scope">
                        <el-button class="preview-button" type="text" @click="handleDet(scope.row)">{{scope.row.name}}</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="近似词" show-overflow-tooltip>
                      <template slot-scope="scope">
                        <div v-if="scope.row.simWords.length>1">
                          <span v-for="k in scope.row.simWords" :key="k">{{k+','}}</span>
                        </div>
                        <div v-if="scope.row.simWords.length===1">
                          <span v-for="k in scope.row.simWords" :key="k">{{k}}</span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="状态">
                      <template slot-scope="scope">
                        <span>{{ formatStatus(scope.row.state) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="创建人">
                      <template slot-scope="scope">
                        <span>{{ scope.row.creater }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="更新人">
                      <template slot-scope="scope">
                        <span>{{ scope.row.updater }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="创建时间">
                      <template slot-scope="scope">
                        <span>{{ scope.row.createTime }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="更新时间">
                      <template slot-scope="scope">
                        <span>{{ scope.row.updateTime }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" :label="$t('table.actions')" width="150" class-name="small-padding fixed-width">
                      <template slot-scope="scope">
                        <el-tooltip content="编辑" placement="top">
                          <el-button :loading="(scope.row.editLoading = false)" class="button-icon el-icon-edit" type="primary" size="mini" @click="handleShowEditor(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                          <el-button :loading="(scope.row.editLoading = false)" class="button-icon el-icon-delete" type="primary" size="mini" @click="handleTableDelete(scope.row)"></el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="pagination-container">
                    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[10, 20, 30, 50]"
                      :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
                    </el-pagination>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <el-dialog :title="textMap[tabledialogStatus]" :visible.sync="dialogFormVisible" width="50%" append-to-body :close-on-click-modal="false">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" label-position="left" label-width="130px" style="margin: 24px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签代码" prop="newsPlateCodes1">
              <el-input v-model="dataForm.tagCode" disabled type="text" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="股票代码" prop="code">
              <el-input v-model="dataForm.code" type="text" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="股票名称" prop="name">
          <el-input v-model="dataForm.name" type="text" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="近似词" prop="dbHost">
          <el-tag :key="tag" v-for="tag in dataForm.s_words" closable :disable-transitions="false" @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="dbHost">
          <el-switch v-model="dataForm.state" active-color="#13ce66" :active-value="1" :inactive-value="0" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        <el-form-item label="基金标签" prop="dbHost">
<!--          <el-select v-model="dataForm.fundRelate" filterable remote reserve-keyword :remote-method="remoteMethod1" :loading="loading" multiple placeholder="请选择">-->
<!--            <el-option v-for="item in options1" :key="item.tagCode" :label="item.name" :value="item.tagCode">-->
<!--            </el-option>-->
<!--          </el-select>-->
          <el-tag v-for="item in options1" :key="item.code">{{item.name+" "+(item.ratio?" ("+item.code+","+item.ratio+'%)':item.code)}}</el-tag>
        </el-form-item>
        <el-form-item label="可转债">
<!--          <el-select v-model="dataForm.bondRelate" filterable remote reserve-keyword :remote-method="remoteMethod2" :loading="loading" multiple placeholder="请选择">-->
<!--            <el-option v-for="item in options2" :key="item.tagCode" :label="item.name+'('+item.code+')'" :value="item.tagCode">-->
<!--            </el-option>-->
<!--          </el-select>-->
          <el-tag v-for="item in options2" :key="item.code">{{item.name+' ('+item.code+')'}}</el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closedig">
          {{
          $t('table.cancel')
          }}
        </el-button>
        <el-button v-if="tabledialogStatus == 'create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="detailstitle" :visible.sync="dialogdetails" :fullscreen='true' :close-on-click-modal="false">
      <labelDetails :tagDetails='tagDetails' :tagType='tagType'></labelDetails>
    </el-dialog>
  </div>
</template>

<script>
import {
  getClassifylist,
  getTagslist,
  getTagsdetail,
  getTagNewsGraph,
  TagsupdateState,
  addTags,
  findstock,
  delTags,
  updateTags,
  findfund,
  addClassify,
  updateClassify,
  delClassify,
  fileparse,
} from "../../api/label";
import { tagsSearch } from "../../api/article";
import { baseUrl, doRequestPost } from "@/utils/request";
import labelDetails from "./labelDetails.vue";
export default {
  name: "stockProperty",
  components: { labelDetails },
  data() {
    return {
      tagType:'stock',
      filterText: "",
      testPass: false,
      treedata: [],
      tagDetails: {},
      options: [],
      options1: [],
      options2: [],
      listQuery: {
        name: "",
        classCode: "",
        similarWord: "",
        state: "",
        code: "",
        pageNum: 1,
        pageSize: 20,
      },
      treefrom: {
        name: "",
        id: "",
        code: "",
      },
      defaultProps: {
        children: "list",
        label: "name",
        id: "id",
      },
      uploadAction: baseUrl + "file/upload",
      uploadFileInfo: {
        loading: false,
        status: "",
      },
      downloadInfo: {
        url: baseUrl + "template/标签模板_股票.xlsx?time="+Math.random(),
        name: "股票标签上传模板",
      },
      multipleSelection: [],
      dialogFormVisible: false,
      treedialogFormVisible: false,
      listLoading: false,
      tableData: [],
      dataForm: {
        code: "",
        tagCode: "",
        name: "",
        classCode: "",
        s_words: [],
        state: 1,
        stockRelate: [],
        fundRelate: [],
        bondRelate: [],
      },
      total: 0,
      rules: {
        name: [
          {
            type: "string",
            required: true,
            message: "请输入...",
            trigger: "change",
          },
        ],
        code: [
          {
            type: "string",
            required: true,
            message: "请输入...",
            trigger: "change",
          },
        ],
      },
      temp: {
        name: 1232,
      },
      value: true,
      textMap: {
        update: "编辑",
        create: "新增",
      },
      dialogStatus: "",
      tabledialogStatus: "",
      detailstitle: "",
      dialogdetails: false,
      inputVisible: false,
      inputValue: "",
      stockcodeOptions: [],
      stocknameOptions: [],
      loading: false,
      timer:null
    };
  },
  props: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {},
  methods: {
     debounce(fn,wait){
       let  that = this;
      return function(){
        if(that.timer!==null){
          clearTimeout(that.timer)
        }
        that.timer = setTimeout(fn,wait);
      }
    },
    remoteMethodcode(query) {
       let  that = this;
      const loadOptions = ()=>{
        if (query !== "") {
          this.loading = true;
          tagsSearch({
            type: "stock",
            code: query,
            classCode: this.listQuery.classCode,
          }).then((res) => {
            let list = res.Data.map((i) => {
              return {
                ...i,
                tag_code: i.tagCode,
              };
            });
            this.loading = false;
            this.stockcodeOptions = list;
          });
        } else {
          this.loading = false;
          this.stockcodeOptions = [];
        }
      }
      this.debounce(loadOptions,2000)()
    },
    remoteMethodname(query) {
      let  that = this;
      const loadOptions = ()=>{

        if (query !== "") {
          this.loading = true;
          tagsSearch({
            type: "stock",
            name: query,
            classCode: this.listQuery.classCode,
          }).then((res) => {
            let list = res.Data.map((i) => {
              return {
                ...i,
                tag_code: i.tagCode,
              };
            });
            that.loading = false;
            that.stocknameOptions = list;
          });
        } else {
          that.loading = false;
          that.stocknameOptions = [];
        }
      }
      this.debounce(loadOptions,2000)()
    },
    getTree() {
      getClassifylist({
        key: "",
        pageNum: 0,
        pageSize: 0,
        type: "stock",
      }).then((res) => {
        this.treedata = res.Data;
      });
    },
    getList() {
      getTagslist({
        classCode: this.listQuery.classCode,
        name: this.listQuery.name,
        pageSize: this.listQuery.pageSize,
        pageNum: this.listQuery.pageNum,
        s_words:
          this.listQuery.similarWord.length > 0
            ? [this.listQuery.similarWord]
            : [],
        state: this.listQuery.state,
        code: this.listQuery.code,
      }).then((res) => {
        this.tableData = res.Data[0].records;
        this.total = res.Data[0].total;
      });
    },
    resetSearch() {
      (this.listQuery.name = ""),
        (this.listQuery.similarWord = ""),
        (this.listQuery.state = ""),
        (this.listQuery.code = ""),
        (this.listQuery.pageNum = 1);
      this.getList();
    },
    filterNode(value, data) {
      if (!value) return true;
      return (
        data.name.indexOf(value) !== -1 ||
        pinyin(data.name, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true,
        })
          .join("")
          .indexOf(value) !== -1
      );
    },
    cleardel(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].list.length > 0) {
          this.cleardel(data[i].list);
        } else {
          delete data[i].list;
        }
      }
      return data;
    },
    getNodeData(data) {
      this.listQuery.classCode = data.code;
      this.dataForm.classCode = data.code;
      this.getList();
    },
    handleAdd() {
      if (this.listQuery.classCode) {
        this.tabledialogStatus = "create";
        this.dialogFormVisible = true;
      } else {
        this.$message.error("请选择一个分类");
      }
    },
    handleStart: function () {
      if (this.multipleSelection.length === 0) return;
      TagsupdateState({
        tagCodeList: this.multipleSelection,
        state: 1,
      }).then(() => {
        this.getList();
        this.$notify({
          title: "成功",
          message: "启用成功",
          type: "success",
          duration: 2000,
        });
      });
    },
    handleStop() {
      if (this.multipleSelection.length === 0) return;
      TagsupdateState({
        tagCodeList: this.multipleSelection,
        state: 0,
      }).then(() => {
        this.getList();
        this.$notify({
          title: "成功",
          message: "停用成功",
          type: "success",
          duration: 2000,
        });
      });
    },
    alldelete() {
      if (this.multipleSelection.length === 0) return;
      this.$confirm("确定删除这些数据？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delTags({
            tagCodeList: this.multipleSelection,
          }).then((res) => {
            if (res.Meta.Code === 0) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    formatStatus(data) {
      switch (data) {
        case 1:
          return "启用";
        case 0:
          return "停用";
      }
    },
    startParse(response, file, fileList) {
      console.log(response, file, fileList);
      this.uploadFileInfo.status = "解析中...";
      fileparse({
        operateType: 3,
        fileName: response.Data[0].fileName,
        code: this.listQuery.classCode,
      })
        .then((res) => {
          this.getList();
          this.$alert(
            "本次导入影响数据" + res.Data[0].successNum + "条",
            "提示",
            {
              confirmButtonText: "确定",
              type: "success",
            }
          );
          const clearFile = () => {
            fileList.splice(fileList.indexOf(file), 1);
          };
          setTimeout(clearFile, 5000);
          this.uploadFileInfo.loading = false;
        })
        .catch(() => {
          this.uploadFileInfo.loading = false;
          this.$refs.uploadButton.clearFiles();
        });
    },
    beforeUpload() {
      if (!this.listQuery.classCode) {
        this.$message.error("请选择一个分类");
        return false;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((i) => i.tagCode);
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    filterNode2(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleShowEditor(data) {
      this.dialogFormVisible = true;
      this.tabledialogStatus = "update";
      this.options = data.stockRelate;
      this.options1 = data.fundRelate;
      this.options2 = data.bondRelate;
      let list = JSON.parse(JSON.stringify(data));
      this.dataForm = {
        code: list.code,
        name: list.name,
        classCode: list.classCode,
        tagCode: list.tagCode,
        s_words: list.simWords,
        state: list.state,
        stockRelate: list.stockRelate.map((i) => i.tagCode),
        fundRelate: list.fundRelate.map((i) => i.tagCode),
        bondRelate: list.bondRelate.map((i) => i.tagCode),
      };
    },
    closedig() {
      this.dialogFormVisible = false;
      this.dataForm = {
        code: this.copydataForm,
        name: "",
        classCode: this.listQuery.classCode,
        s_words: [],
        state: 1,
        stockRelate: [],
        fundRelate: [],
        bondRelate: [],
      };
    },
    handleTableDelete(data) {
      this.$confirm("确定删除本条数据？", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delTags({
            tag_code: data.tagCode,
          }).then((res) => {
            if (res.Meta.Code === 0) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDet(data) {
      this.detailstitle = data.name;
      this.tagDetails = data;
      this.dialogdetails = true;
    },
    remoteMethod1(query) {
      if (query !== "" && !this.loading) {
        this.loading = true;
        tagsSearch({
          type: "fund",
          key: query,
        }).then((res) => {
          this.loading = false;
          this.options1 = res.Data;
        });
      } else {
        this.options1 = [];
      }
    },
    remoteMethod2(query) {
      if (query !== "" && !this.loading) {
        this.loading = true;
        tagsSearch({
          type: "bond",
          key: query,
        }).then((res) => {
          this.loading = false;
          this.options2 = res.Data;
        });
      } else {
        this.options2 = [];
      }
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addTags("stock", this.dataForm).then((res) => {
            if (res.Meta.Code === 0) {
              this.getList();
              this.$message.success("添加成功");
            } else {
              this.$message.error(res.Meta.Message);
            }
            this.closedig();
          });
        } else {
          return false;
        }
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateTags("stock", this.dataForm).then((res) => {
            if (res.Meta.Code === 0) {
              this.getList();
              this.$message.success("编辑成功");
            } else {
              this.$message.error(res.Meta.Message);
            }
            this.closedig();
          });
        } else {
          return false;
        }
      });
    },
    handleClose(tag) {
      this.dataForm.s_words.splice(this.dataForm.s_words.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      const inputValue = this.inputValue;
      if (inputValue) {
        this.dataForm.s_words.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
  },
  mounted() {
    this.getTree();
  },
  destroyed() {},
};
</script>

<style lang="stylus" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
<style>
.stockProperty
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff;
  color: #ffffff;
}
</style>
